const fs = require('fs');
const inquirer = require('inquirer'); // 命令行交互询问模块
const chalk = require('chalk'); // 颜色增强模块
const ora = require('ora'); // 命令行加载效果
const download = require("download-git-repo");
const handlebars = require('handlebars');
const projectType = require('./config.js').config; // 询问配置

module.exports = name => {
  if (fs.existsSync(name)) {
    console.log(chalk.red('文件夹名已被占用，请更换name重新创建'));
    return;
  }
  inquirer.prompt(projectType).then((answers) => {
    const spinner = new ora({text:'downloading...',spinner:'growVertical',color:'green'});
        spinner.start()
    // 下载项目;
    download(`https://gitee.com:jz07/${answers.type}`,
    name,
      { clone: true },
      err => {
        if (!err) {
			spinner.succeed();
			const fileName = `${name}/package.json`;
			const meta = {
				name,
				description: answers.description,
				author: answers.author
			}
			if (fs.existsSync(fileName)) {
				const content = fs.readFileSync(fileName).toString();
				const result = handlebars.compile(content)(meta);
				fs.writeFileSync(fileName, result);
			}
			console.log(chalk.green('项目初始化完成'));
        }
        else{
          spinner.fail()
		  console.log(chalk.red(err))
        }
      }
    );
  })
}
